# -*- coding:utf-8 -*-
"""
大萌资讯
https://www.damenginfo.com/category/blockchain

"""
import requests
import re
import time
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=60, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_qkl(url):
    text = get_html_text(url)
    if not text:
        return None
    regex = re.compile(r'<span class="item-meta-li date">([\s\S]*?)</span>')
    dates = re.findall(regex, text)
    return dates


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    h = time.strftime("%H", time.localtime())
    while 1:
        url = 'https://www.damenginfo.com/category/blockchain/page/{}'.format(a)
        dates = get_dates_qkl(url)
        print('----大萌资讯区块链获取第{}页----'.format(a))
        if not dates:
            break
        for date in dates:
            if '分钟前' in date:
                d1 += 1
            elif ('小时前' in date) and (date[:-3] < h):
                d1 += 1
            elif ('小时前' in date) and (date[:-3] >= h):
                d2 += 1
            elif '1天前' in date:
                d2 += 1
            elif '2天前' in date:
                d3 += 1
            else:
                d4 += 1
        if d4 != 0:
            break
    return (d1, d2, d3)


def main():
    u = '大萌资讯'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
